<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div>
    <a-tabs @change="searchState" v-model:active-key="selectState" type="line">
      <a-tab-pane :key="1" title="待确认出库单"> </a-tab-pane>
      <a-tab-pane :key="2" title="备货并检验"> </a-tab-pane>
      <a-tab-pane :key="3" title="确认出库"> </a-tab-pane>
      <a-tab-pane :key="4" title="异常处理"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-group>
          <!-- <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
            :default-value="currSelectVal"
          >
            <a-option value="outboundNumber">出库单编号</a-option>
          </a-select> -->
          <a-input-search
            search-button
            :style="{ width: 'auto' }"
            placeholder="请输入出库单编号"
            v-model="currSelectSearch"
            @search="search"
          />
        </a-input-group>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="180"
        align="center"
      >
        <template v-if="item.code === 'outboundDate'" #cell="{ record }">
          {{
            record.outboundDate
              ? dayjs(record.outboundDate).format('YYYY-MM-DD')
              : '--'
          }}
        </template>

        <template v-else-if="item.code === 'staffName'" #cell="{ record }">
          {{ record.staffName || '--' }}
        </template>

        <template v-else-if="item.code === 'CreatedAt'" #cell="{ record }">
          {{
            record.CreatedAt
              ? dayjs(record.CreatedAt).format('YYYY-MM-DD')
              : '--'
          }}
        </template>

        <template v-else-if="item.code === 'consigneeInfo'" #cell="{ record }">
          {{ record.consigneeName }}/{{ record.consigneePhone }}
        </template>

        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <a-typography-text v-if="record.state === 1" style="color: #999999">
            预收获
          </a-typography-text>
          <a-typography-text v-else type="success"> 已收货 </a-typography-text>
        </template>
      </a-table-column>

      <a-table-column v-if="selectState === 2" title="备货状态" align="center"
        ><template #cell="{ record }">
          <a-typography-text v-if="record.state === 2" disabled>
            待备货</a-typography-text
          >
          <a-typography-text type="primary" v-if="record.state === 3">
            备货中</a-typography-text
          >
          <a-typography-text type="success" v-if="record.state === 4">
            备货完成</a-typography-text
          >
        </template>
      </a-table-column>

      <a-table-column
        v-if="selectState === 3"
        :width="200"
        title="质检状态"
        align="center"
      >
        <template #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter(
                (ele) => ele.id === record.inspectionState
              )[0]?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.inspectionState
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{
              orderStatus.filter((ele) => ele.id === record.inspectionState)[0]
                ?.value
            }}
          </div>
          <!-- <a-typography-text
            v-if="record.inspectionState === 1"
            style="color: #999999"
          >
            待质检
          </a-typography-text>
          <a-typography-text
            v-else-if="record.inspectionState === 2"
            type="success"
          >
            质检通过
          </a-typography-text>
          <a-typography-text
            v-else-if="record.inspectionState === 3"
            type="primary"
          >
            部分通过质检 </a-typography-text
          ><a-typography-text
            v-else-if="record.inspectionState === 4"
            type="danger"
          >
            质检不通过
          </a-typography-text> -->
        </template>
      </a-table-column>

      <a-table-column :width="250" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <a-tooltip content="查看详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDeliveryDetails(record.id)"
            />
          </a-tooltip>

          <a-tooltip
            v-if="
              record.state === 5 &&
              record.inspectionState === 2 &&
              record.invoiceState === 1
            "
            content="创建发货单"
          >
            <IconFont
              type="icon-add-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="setShipment(record.id)"
            />
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="委外出库列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
  <ProcessesOutsourcingShipping
    v-if="processesVisible"
    v-model:visible="processesVisible"
    :id="ShipmentId"
    :outsourcingId="outsourcingId"
    @processesInvoiceEdit="ProcessesInvoiceEdit"
  ></ProcessesOutsourcingShipping>
  <ProductOutsourcingShipping
    v-if="productVisible"
    v-model:visible="productVisible"
    :id="ShipmentId"
    @postInvoiceEdit="ProductInvoiceEdit"
  ></ProductOutsourcingShipping>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getOutboundAll,
    postInvoice,
  } from '@/api/inventory-management/outbound-management/sales-shipment-outbound/sales-outbound/index';
  import { postOutsourcingInvoice } from '@/api/inventory-management/outbound-management/sales-shipment-outbound/sales-outbound/index';
  import {
    getHeader,
    PostHeader,
  } from '@/api/inventory-management/header-management/index';
  import ProcessesOutsourcingShipping from './ProcessesOutsourcingShipping.vue';
  import ProductOutsourcingShipping from './ProductOutsourcingShipping.vue';
  // import ShipmentModel from './create-shipment-order/index.vue';

  const selectState = ref(1);
  const router = useRouter();
  const title: string = '委外出库';
  const outsourcingId = ref(null);
  const breadCrumb: string[] = ['库存管理', '出库管理', '委外出库'];
  const productVisible = ref(false);
  const processesVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const beginTime = ref();
  const endTime = ref();
  const ownList = ref();
  const saveUserId = ref<any>(
    JSON.parse(sessionStorage.getItem('loginInfo') as any)
  );
  const ShipmentId = ref();

  // 表格配置
  const args = reactive({
    stripe: true,
    scroll: {
      y: 2000,
      x: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const orderStatus = [
    { id: 1, value: '待质检', backgroundColor: '#cccccc' },
    { id: 2, value: '质检通过', backgroundColor: '#009933' },
    { id: 3, value: '部分质检通过', backgroundColor: '#009933' },
    { id: 4, value: '质检不通过', backgroundColor: '#009933' },
  ];

  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (selectState.value) msg.state = selectState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (ownList.value) msg.ownList = ownList.value;
      let res = await getOutboundAll({
        ...page,
        ...msg,
        outboundType: 3,
      });
      if (res.content === null || res.content === undefined) {
        res.content = [];
      }

      res.content.map((item: any) => {
        item.show = false;
        return item;
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const columns = [
    {
      code: 'number',
      isDefault: 1,
      name: '委外出库单号',
    },
    {
      code: 'orderNumber',
      isDefault: 1,
      name: '关联委外单号',
    },
    {
      code: 'supplierName',
      isDefault: 1,
      name: '供应商名称',
    },
    {
      code: 'consigneeInfo',
      isDefault: 1,
      name: '收货人/联系电话',
    },
    {
      code: 'consigneeAddress',
      isDefault: 1,
      name: '收货地址',
    },

    {
      code: 'staffName',
      isDefault: 1,
      name: '收货日期',
    },
    {
      code: 'staffName',
      isDefault: 1,
      name: '下达人',
    },
    {
      code: 'outboundDate',
      isDefault: 1,
      name: '下达时间',
    },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const headerSettingData = async () => {
    try {
      const res = await getHeader({
        userId: saveUserId.value.id,
        listType: 10,
      });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    priorityData.value = undefined;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const searchState = (val: number) => {
    reset();
  };
  const search = (val: number) => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: saveUserId.value.id,
        listType: 10,
        extend: JSON.stringify(val),
      };
      await PostHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const addOutbound = (e?: number) => {
    router.push({
      name: 'AddSalesOutbound',
    });
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const setShipment = (val: any) => {
    if (val.outboundType === 4) {
      processesVisible.value = true;
      ShipmentId.value = val.id;
      outsourcingId.value = val.outsourcingId;
    } else {
      productVisible.value = true;
      ShipmentId.value = val.id;
    }
  };

  const goDeliveryDetails = async (id: number) => {
    router.push({
      name: 'ProduceOutsourcingOutboundDetails',
      query: { id },
    });
  };

  const ProcessesInvoiceEdit = async (form?: any) => {
    await postOutsourcingInvoice({ ...form });
    tableRef.value.loadData();
    ShipmentId.value = undefined;
  };

  const ProductInvoiceEdit = async (outboundWarehouseItem?: any) => {
    await postInvoice({ outboundWarehouseItem });
    tableRef.value.loadData();
    ShipmentId.value = undefined;
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .Detail-item {
    cursor: pointer;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
